#!/usr/bin/python3
# -*- coding: utf-8 -*-
import django_filters
from clogger import logger
from rest_framework.filters import BaseFilterBackend
from apps.task.models import JobModel


class TaskFilter(django_filters.FilterSet):
    service_name = django_filters.CharFilter(field_name="service_name")
    # https://stackoverflow.com/questions/58977818/how-to-use-django-filter-on-jsonfield
    channel = django_filters.CharFilter(field_name="params__channel")

    class Meta:
        model = JobModel
        fields = ["id", "task_id", "created_by__id", "status"]


class IsOwnerFilterBackend(BaseFilterBackend):
    """
    Filter that only allows users to see their own objects.
    """

    def filter_queryset(self, request, queryset, view):
        if request.user is None and request.method == "GET":
            return queryset
        user_id = request.user.get("id", None)
        is_admin = request.user.get("is_admin", False)
        if is_admin:
            return queryset
        else:
            return queryset.filter(created_by=user_id)
